<template>
    <div>
        <NavBar>
            <template #default>
                购物车
            </template>
        </NavBar>
        <ShopCartList
            :shopCartData="shopStore.cartItems"
            @changeShopCartData="changeShopCart"
            @changeNumber="changeProductNumber"
            @deleteProduct="deleteGoalProduct"
        />
        <CheckoutBar
            :shopCartData="shopStore.cartItems"
        />
    </div>
</template>

<script setup>
import NavBar from '../../components/common/NavBar.vue';
import ShopCartList from '../../components/content/ShopCartList.vue';
import CheckoutBar from '../../components/content/CheckoutBar.vue';
import { computed, ref, onMounted, onActivated, watch } from 'vue';
import { useShopStore } from '../../stores/shop.js';
import { showToast } from 'vant';
import { useRouter } from 'vue-router';

const shopStore = useShopStore();
const router = useRouter();

// 购物车数据初始化函数 - 使用智能缓存策略
const initCartData = async () => {
    try {
        // 使用智能刷新：只在数据变更时从服务器同步
        await shopStore.smartRefreshCart();

        // 为每个购物车项添加 'checked' 属性，默认为 false
        shopStore.cartItems.forEach(item => {
            // 确保只在 item 还没有 checked 属性时才添加，避免重复设置
            if (typeof item.checked === 'undefined') {
                item.checked = false;
            }
        });

        // 显示数据来源信息
        const dataSource = shopStore.isDataDirty ? '🌐 服务器数据' : '📦 本地缓存';
        console.log(`购物车数据加载完成 (${dataSource}):`, shopStore.cartItems);
    } catch (error) {
        showToast({
            message: error.message,
            duration: 1500,
            forbidClick: true,
        });
    }
};

// 组件挂载时初始化
onMounted(async () => {
    console.log('🛒 购物车页面加载中...');
    await initCartData();
});

// 每次激活组件时智能刷新（如从其他页面返回）
onActivated(async () => {
    console.log('🔄 购物车页面被激活，检查是否需要同步...');
    await initCartData();
});

// 处理单个商品选中状态变化
const changeShopCart = (cartId, checked) => {
    const item = shopStore.cartItems.find(item => item.cartId === cartId);
    if (item) {
        item.checked = checked;
        // 保存到本地存储
        shopStore.saveCartToLocalStorage();
    }
};

// 处理商品数量变化
const changeProductNumber = async (cartId, operation) => {
    const item = shopStore.cartItems.find(item => item.cartId === cartId);
    if (!item) return;

    let newQuantity = item.quantity;
    if (operation === '+') {
        newQuantity += 1;
    } else if (operation === '-' && newQuantity > 1) {
        newQuantity -= 1;
    } else {
        return; // 数量不能小于1
    }

    try {
        await shopStore.updateCartItemQuantity(cartId, newQuantity);
        showToast({
            message: '数量已更新',
            duration: 1000,
        });
    } catch (error) {
        showToast({
            message: error.message || '更新失败',
            duration: 1500,
        });
    }
};

// 处理删除商品
const deleteGoalProduct = async (cartId) => {
    try {
        await shopStore.removeCartItem(cartId);
        showToast({
            message: '商品已移除',
            duration: 1000,
        });
    } catch (error) {
        showToast({
            message: error.message || '删除失败',
            duration: 1500,
        });
    }
};
</script>

<style lang="scss" scoped>
// 你的样式保持不变
</style>